package com.lbjhan.rpc.consumer.client;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.List;

public class RpcZKClient {
    private CuratorFramework zk_client;
    private static volatile RpcZKClient rpcZKClient = null;

    private RpcZKClient(){
        init();
    }

    public static RpcZKClient getInstance(){
        if(rpcZKClient == null){
            synchronized (RpcZKClient.class){
                if(rpcZKClient == null){
                    rpcZKClient = new RpcZKClient();
                }
            }
        }
        return rpcZKClient;
    }

    public void init(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        zk_client = CuratorFrameworkFactory.builder()
                .connectString("101.200.199.134:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(retryPolicy)
                .namespace("rpc")
                .build();
        zk_client.start();
    }

    public String getIpPort(String serviceName) throws Exception {
        List<String> list = zk_client.getChildren().forPath("/" + serviceName);
        return list.get(0);
    }
}
